package com.party.web.biz.photo;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.api.dto.wechat.requst.XcxQrCodeRequest;
import com.party.common.constant.Constant;
import com.party.common.utils.StringUtils;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.photo.PhotoProject;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IThirdMemberService;
import com.party.core.service.photo.IPhotoProjectService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.web.biz.file.FileBizService;
import com.party.web.biz.openPlatform.NotifyBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 相册
 *
 * @author yifeng
 * @date 2018/9/5 0005
 * @time 下午 18:53
 */
@Service
public class PhotoBizService {
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IPhotoProjectService photoProjectService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private NotifyBizService notifyBizService;
    @Autowired
    private IThirdMemberService thirdMemberService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    Logger logger = LoggerFactory.getLogger(getClass());

    public Map<String, String> getReturnUrl(String memberId) {
        Map<String, String> map = Maps.newHashMap();
        if (StringUtils.isNotEmpty(memberId)) {
            List<String> partnerIds = projectService.getPartnerIdByAuthorId(memberId);
            if (partnerIds.size() > 0) {
                List<PhotoProject> photoIds = photoProjectService.batchByMember(new HashSet<>(partnerIds), null);
                if (photoIds.size() == 1) {
                    map.put("type", "image");
                    map.put("value", photoIds.get(0).getId());
                    return map;
                }
            }
        }
        map.put("type", "url");
        map.put("value", "photo/my_list.html");
        return map;
    }

    public String uploadTempMedia(String projectId) throws Exception {
        PhotoProject signProject = photoProjectService.get(projectId);
        String filePath = fileBizService.getUploadCIPath(signProject.getMemberId(), "photo");
        String url = cosBizService.getPreviewPictureUrl(filePath + signProject.getId());
        return notifyBizService.uploadTempMedia(url, signProject.getMemberId());
    }

    /**
     * 生成信息
     * @param photoId 项目id
     * @return
     */
    public Map<String, Object> generateInfo(String photoId) {
        Map<String, Object> result = Maps.newHashMap();
        Integer account = (int) ((Math.random() * 9 + 1) * 100000);
        List<String> thirdList = thirdMemberService.allAccount();
        List<Integer> lists = Lists.newArrayList();
        generateAccount(thirdList, account, lists);
        result.put("account", lists.get(0));
        String password = getStringRandom(6);
        result.put("password", password.toLowerCase());
        String alias = "/photo/album/third/";
        String url = alias + "list.do?photosId=" + photoId;
        result.put("url", url);
        result.put("alias", alias);
        return result;
    }

    public boolean generateAccount(List<String> thirdList, Integer account, List<Integer> lists) {
        lists.add(account);
        boolean flag = true;
        for (String str : thirdList) {
            if (account.toString().equals(str)) {
                flag = false;
                lists.remove(Integer.valueOf(str));
                break;
            } else {
                flag = true;
            }
        }

        if (flag == false) {
            account = (int) ((Math.random() * 9 + 1) * 100000);
            flag = generateAccount(thirdList, account, lists);
        }
        return flag;
    }

    /**
     * 生成随机数字和字母,
     * @param length
     * @return
     */
    public String getStringRandom(int length) {
        String val = "";
        Random random = new Random();

        //参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /**
     * 迁移行知公社发布的相册到子账号下
     *
     * @param title        查询的标题
     * @param xzgsMemberId 行知公社用户id
     * @param username     子账号的用户名
     * @author yifeng
     * @date 11:05 2019/11/12
     **/
    public void xzgsPhotoDataMigration(String title, String xzgsMemberId, String username) {
        String memberId = "";
        List<String> projectIds = photoProjectService.getXzgsPhotoList(title, xzgsMemberId);
        if (projectIds.size() > 0) {
            MemberGroup memberGroup = memberGroupService.findByUserName(username);
            memberId = memberGroup.getId();
        }
        for (String projectId : projectIds) {
            photoProjectService.updateMember(projectId, memberId);

            this.uploadQrCode(projectId, memberId);
        }
    }

    /**
     * 上传相册小程序码
     *
     * @param projectId 项目id
     * @param memberId  用户id
     * @author yifeng
     * @date 17:15 2019/11/12
     **/
    public void uploadQrCode(String projectId, String memberId) {
        try {
            WechatOpenMember openMember = wechatOpenMemberService.findByType(Constant.WECHAT_ACCOUNT_TYPE_SYSTEM_XCX_PHOTO);
            XcxQrCodeRequest qrCodeRequest = new XcxQrCodeRequest();
            qrCodeRequest.setPage("pages/photo/index");
            qrCodeRequest.setScene(projectId);
            String filePath = fileBizService.getUploadCIPath(memberId, "photo");
            fileBizService.uploadCloudOut(projectId, filePath, qrCodeRequest, openMember.getAuthorizerAccessToken(), 1);
        } catch (Exception e) {
            logger.error("生成小程序码异常", e);
        }
    }
}
